<?php


namespace app\admin\controller\distributor;

use app\api\controller\Order;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * 
 */
class Distributor extends AdminController
{
    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\Distributor();
        
    }
    
    /**
     * 分销商列表
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                foreach ($list as $k => $v){
                    //用户
                    $user = Db::name('user')->where('id',$v['uid'])->field('nickname,avatar')->find();
 
                    $v['nickname'] = $user['nickname'];
                    $v['avatar'] = $user['avatar'];

                    $promotion_number = Db::name("user")->where("superior_fid",$v["id"])->count();

                    $v['promotion_number'] = $promotion_number;
                    $list[$k] = $v;
                }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();

    }

    /**
    * @NodeAnotation(title="编辑")
    */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['phone'])){
                $this->error('手机号不能为空');
            }
            $data = [
                'phone'=>$post['phone'],
                'age'=>$post['age'],
                'card'=>$post['card']
            ];
            try { 
               $this->model->where('id',$post['id'])->update($data);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功') ;
        }else{
            $post = $this->request->param(); 
            $row = $this->model->where('id',$post['id'])->find();
            $this->assign('row', $row);
        }
        return $this->fetch();
    }

     /**
    * @NodeAnotation(title="通过")
    */
    public function adopt_url()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ret = $this->model->where('id', $post['id'])->where('status', 0)->where('examine', 0)->find();
            if (empty($ret)) {
                $this->error('当前状态不能审核');
            }
            $ret = $ret->toArray();
            $this->model->where('id', $post['id'])->update(['examine' => 1]);
            Db::name('user')->where('id',$ret['uid'])->update(['fid'=>$post['id']]);
            //生成分销商二维码
            $seg = $this->wxapp_url($post['id'],$ret['uid']);
            if($seg["code"] == 1){
                $this->success('审核成功', '');
            }else{
                $this->error($seg["msg"]);
            }
        }
        return $this->fetch();
    }

    /**
    * @NodeAnotation(title="驳回")
    */
    public function reject_url()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post["reason_for_rejection"])){
                $this->error("驳回原因不能为空");
            }
            $ret = $this->model->where('id', $post['id'])->where('status', 0)->where('examine', 0)->find();
            if (empty($ret)) {
                $this->error('当前状态不能审核');
            }
            $this->model->where("id",$post["id"])->update(["examine"=>2,"reason_forejection"=>$post["reason_for_rejection"]]);
            $this->success('驳回成功', '');
        }
        return $this->fetch();
    }

    /**
    * @NodeAnotation(title="查看下级成员")
    */
    public function looksub_url()
    {
        $post = $this->request->param();
       
        $user = Db::name("user")
            ->where("superior_fid",$post["id"])
            ->field("id,nickname")
            ->paginate(20)->each(function($item){
                $order_num = Db::name("order")->where("uid",$item["id"])->where("status","in","4,7")->count();
                $order_money = Db::name("order")->where("uid",$item["id"])->where("status","in","4,7")->sum("paidin_money");
                $item["order_num"] = $order_num; 
                $item["order_money"] = $order_money; 
                return $item;
            });
//        $user = $user->toArray();
        $data = ['code' => '1', 'msg' => '获取成功','data'=>$user];
        return json($data);
//        return [
//            "code"=>1,
//            "msg"=>"获取成功",
//            "data"=>$user
//        ];
//        $this->assign("data",$user["data"]);
//        return $this->fetch();
    }

    /**
     *生成小程序二维码
     * 
     */
    public function wxapp_url($hid,$ret_uid){
        if(empty($hid)){
           return [
               "code"=>-1,
               "msg"=>"分销商id不能为空",
               "data"=>""
           ];
        }
        //查询二维码是否已生成
        $user = Db::name("user")->where("id",$ret_uid)->where("fid",">",0)->find();
        if(empty($user)){
            return [
                "code"=>-1,
                "msg"=>"您还不是分销商，请申请",
                "data"=>""
            ];
        }
        if(!empty($user["qrcode"])){
            return [
                "code"=>1,
                "msg"=>"二维码已生成",
                "data"=>$user["qrcode"]
            ];
        }
        $appid = "wxfaeec6c5fc3fa560";
        $appSecret = "d1a706544522c6f1336cf8dcb8f370e9";
        header('content-type:text/html;charset=utf-8');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
        $weix = file_get_contents($url);//获得网页输出
        $obj=json_decode($weix,true );//解码
        $access_token= $obj['access_token'];//网页授权接口调用凭证
 
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";
        $data = json_encode(['scene'=>"fid".$hid,'page'=>"pages/index/index"]);
        $wx = $this->httpRequest($url,$data);
        $domain = ($this->isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']; //获取域名
        $save_path =$domain.'/' .$wx;
        Db::name("user")->where("id",$ret_uid)->update(["qrcode"=>$save_path]);
        return [
            "code"=>1,
            "msg"=>"生成成功",
            "data"=>['qrcode' => $save_path,"uid"=>$hid]
        ];
    }
    function httpRequest($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 'image/gif');
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过ssl检测
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //如果需要将结果直接返回到变量里，那加上这句。
        $res = curl_exec($ch);
        $name = "static/qrcode/".time().".png";
        file_put_contents($name,$res);
        curl_close($ch);
        return $name;
    }

    
 
 
} 